﻿// hookDLLInject.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <Windows.h>
//#include <WinSock2.h>
#include <detours.h>
#pragma comment(lib, "detours.lib")
#pragma comment(lib, "ws2_32.lib")


//主函数带参数，参数为要注入的程序的路径
int main(int argc, char* argv[])
{
    //接收参数
   WCHAR path[MAX_PATH + 1] = { 0 };
   if (argc > 1)
   {
         MultiByteToWideChar(CP_ACP, 0, argv[1], -1, path, MAX_PATH);
    }
   else
   {
         //wcscpy_s(path, MAX_PATH, L"D:\\source\\c++\\RuanJianKeShe\\hust-detours\\APP\\x64\\Debug\\APP.exe");
       wcscpy_s(path, MAX_PATH, L"C:\\Users\\nymph\\Downloads\\Defender-main\\src\\MFCtest\\x64\\Release\\MFCtest.exe");
    }
   STARTUPINFO si;
   PROCESS_INFORMATION pi;
   ZeroMemory(&si, sizeof(STARTUPINFO));
   ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
   si.cb = sizeof(STARTUPINFO);
   WCHAR DirPath[MAX_PATH + 1];
   wcscpy_s(DirPath, MAX_PATH, L"D:\\source\\c++\\RuanJianKeShe\\hust-detours\\hookDLL\\x64\\Release");
   char DLLPath[MAX_PATH + 1] = "D:\\source\\c++\\RuanJianKeShe\\hust-detours\\hookDLL\\x64\\Release\\hookDLL.dll";
   WCHAR EXE[MAX_PATH + 1] = { 0 };
   //将参数写入EXE
   wcscpy_s(EXE, MAX_PATH, path);

   if (DetourCreateProcessWithDllEx(EXE, NULL, NULL, NULL, TRUE, CREATE_DEFAULT_ERROR_MODE|CREATE_SUSPENDED, NULL, DirPath, &si, &pi, DLLPath, NULL))
   {

       
       ResumeThread(pi.hThread);

       printf("CreateProcessWithDllEx success\n");
       printf("Process ID: %d\n", pi.dwProcessId);
       printf("Thread ID: %d\n", pi.dwThreadId);
       printf("EXE Path: %ls\n", EXE);

       WaitForSingleObject(pi.hProcess, INFINITE);
   }
   else
   {
       DWORD dwError = GetLastError();
       LPVOID lpMsgBuf;
       FormatMessage(
           FORMAT_MESSAGE_ALLOCATE_BUFFER |
           FORMAT_MESSAGE_FROM_SYSTEM |
           FORMAT_MESSAGE_IGNORE_INSERTS,
           NULL,
           dwError,
           MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
           (LPTSTR)&lpMsgBuf,
           0, NULL);
       printf("CreateProcessWithDllEx failed with error %d: %s\n", dwError, (LPCTSTR)lpMsgBuf);
       LocalFree(lpMsgBuf);

   }

   return 0;
}
